import React, { useState, useEffect, useRef } from 'react'
import { Form, Input, InputNumber, Switch, Button, Upload, TreeSelect, message, Image } from 'antd'
import { getCates } from '@a/cate'
import {  fetchItemDetail, updateItem } from '@a/item'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { useNavigate, useSearchParams } from 'react-router-dom'
export default function ItemAdd() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  // 修改商品初始值
  const formRef = useRef(null);
  const getItemDetail = () => {
    fetchItemDetail({
      id: searchParams.get('id')
    }).then(res => {
      // 处理表单初始值
      if (res.data.code === 200) {
        formRef.current.setFieldsValue(res.data.data)
        // 封面初始值和 富文本初始值
        setThumb(res.data.data.thumb);
        setHtml(res.data.data.content)
      }
      
    })
  }

  const onSubmit = (params = {}) => {
    updateItem({
      ...params,
      thumb,
      content: html
    }).then((res: { data: { code: number; msg: string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | React.ReactFragment | React.ReactPortal | MessageArgsProps | null | undefined } }) => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          // 回到商品列表
          navigate('/itemLists', {replace: true})
        })
      }
    })
  }
  // 获取分类列表
  const [cates, setCates] = useState([]);
  const fetchCates = () => {
    getCates().then(res => {
      if (res.data.code === 200) {
        setCates(res.data.data)
      }
    })
  }
  useEffect(() => {
    fetchCates();
    getItemDetail();
  }, [])
  // 上传 图片回调
  const [thumb, setThumb] = useState('');
  const uploadStateChange = (info: any) => {
    if (info.file.status === 'done') {
      // 上传完成
      if (info.file.response.code === 200) {
        setThumb(info.file.response.data.url)
      }
    }
  }
  // 富文本编辑器
  const [editor, setEditor] = useState(null);
  // 编辑器内容
  const [html, setHtml] = useState();
  const toolbarConfig = {}
  // 编辑器配置
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/api/upload',
        customInsert(res: any, insertFn) {  // TS 语法
          insertFn(res.data.url)
        },
      }
    }
  }
  // 销毁
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  return (
    <Form
      ref={formRef}
      name="basic"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      initialValues={{ onsale: true }}
      style={{ maxWidth: 800 }}
      onFinish={onSubmit}
    >
      <Form.Item label="商品名" name="itemName" rules={[{ required: true, message: '商品名必填' }]}>
        <Input />
      </Form.Item>
      <Form.Item label="商品价格" name="price" rules={[{ required: true, message: '商品名必填' }]}>
        <InputNumber min={0} />
      </Form.Item>
      <Form.Item
        label="上下架"
        name="onsale"
        valuePropName="checked"
        rules={[
          { required: true, message: '必须选择上下架!' }
        ]}
      >
        <Switch />
      </Form.Item>
      <Form.Item
        label="商品分类"
        name="cateId"
        rules={[
          { required: true, message: '分类必填!' }
        ]}
      >
        <TreeSelect
          showSearch
          style={{ width: '100%' }}
          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
          placeholder="选择商品分类"
          allowClear
          treeDefaultExpandAll
          treeData={cates}
          fieldNames={{
            label: 'cateName',
            value: 'id',
            children: 'children'
          }}
        />
      </Form.Item>
      <Form.Item label="商品描述" name="desc" >
        <Input.TextArea />
      </Form.Item>
      <Form.Item label="分类图标">
        <Upload
          name='file'
          action="/api/upload"
          accept='.jpg, .png, .gif'
          onChange={
            uploadStateChange
          }
        >
          <Button>点击上传</Button>
        </Upload>
        <Image src={thumb} width={100}  />
      </Form.Item>
      <Form.Item label="富文本">
        <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: '1px solid #ccc' }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={editor => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: '500px', overflowY: 'hidden' }}
          />
        </div>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
        <Button htmlType='submit'>提交</Button>
      </Form.Item>
    </Form>
  )
}
